var submit = 2
layui.use(['table', 'admin', 'ax','laydate'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var laydate = layui.laydate;

    laydate.render({
    	elem:'#startTime'
    });
    
    laydate.render({
    	elem:'#endTime'
    });

    /**
     * 云仓入库表管理
     */
    var ToolOrderPut = {
        tableId: "toolOrderPutTable"
    };

    /**
     * 云仓入库明细表管理
     */
    var ToolOrderPutDetailed = {
        tableId: "toolOrderPutDetailedTable"
    };

    /**
     * 初始化表格的列
     */
    ToolOrderPut.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: '主键'},
            {field: 'billstate', sort: true, title: '单据状态',templet: '#billstateTpl'},
            {field: 'putNumber', sort: true, title: '系统单号'},
            {field: 'putCustomerName', sort: true, title: '客户名称'},
            {field: 'putCustomerNumber', sort: true, title: '客户单号'},
            {field: 'warehouseName', sort: true, title: '仓库名称'},
            {field: 'putMode', sort: true, title: '入库方式'},
            {field: 'putType', sort: true, title: '入库类别'},
            {field: 'origin', sort: true, title: '来源地'},
            {field: 'sourceunit', sort: true, title: '来源单位'},
            {field: 'carnumber', sort: true, title: '车牌号', totalRowText: '合计：'},
            {field: 'sumNum', sort: true, title: '总数量', totalRow: true},
            {field: 'sumWeight', sort: true, title: '总重量', totalRow: true},
            {field: 'sumVolume', sort: true, title: '总体积', totalRow: true},
            {field: 'notes', sort: true, title: '备注'},
            {field: 'createTime', sort: true, title: '制单时间'},
            {field: 'createName', sort: true, title: '制单用户'},
            {align: 'center', toolbar: '#tableBar', title: '操作'}
        ]];
    };

    /**
     * 点击查询按钮
     */
    ToolOrderPut.search = function () {
        var queryData = {};
        queryData['condition'] = $("#condition").val();
        queryData['billstate'] = $("#billstate").val();
        queryData['putCustomerId'] = $("#putCustomerId").val();
        queryData['warehouseId'] = $("#warehouseId").val();
        queryData['startTime'] = $("#startTime").val();
        queryData['endTime'] = $("#endTime").val();
        table.reload(ToolOrderPut.tableId, {
            where: queryData, page: {curr: 1},
             done:function () {
            }
        });
    };

    /**
     * 弹出添加对话框
     */
    ToolOrderPut.openAddDlg = function () {
        window.location.href = Feng.ctxPath + '/toolOrderPut/add';
    };

    /**
     * 导出excel按钮
     */
    ToolOrderPut.exportExcel = function () {
        var checkRows = table.checkStatus(ToolOrderPut.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要导出的数据");
        } else {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        }
    };

    /**
     * 点击编辑
     *
     * @param data 点击按钮时候的行数据
     */
    ToolOrderPut.openEditDlg = function (data) {
        window.location.href = Feng.ctxPath + '/toolOrderPut/edit?id=' + data.id;
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + ToolOrderPut.tableId,
        url: Feng.ctxPath + '/toolOrderPut/list',
        page: true,
        limit: 40,
        height: 410,
        toolbar: '#toolbarDemo', //开启头部工具栏，并为其绑定左侧模板
        cellMinWidth: 100,
        totalRow: true ,//开启合计行
        cols: ToolOrderPut.initColumn()
    });

     //批量入库
     $('#btnPut').click(function () {
    	var checkStatus = table.checkStatus('toolOrderPutTable');
        data = checkStatus.data;
        if (data.length>0) {
            var ids = [];
            for (var i = 0; i < data.length; i++) {
				if(data[i].billstate == "待提交" || data[i].billstate == "撤回"){
				} else {
		    		layer.msg('请选择待提交或者撤回单据进行入库'); 
					return
				}
            	ids.push(data[i].id);
			}
			submit = 2
	        layer.open({
	            type: 2,
	            title: '选择存放位置',
	            area: ['850px', '650px'],
	            anim: 5,
	            content: Feng.ctxPath + '/toolOrderPut/tobtnPut?ids='+ids,
	            end: function () {
					if(submit == 1){
            			table.reload(ToolOrderPut.tableId);
					}
	            }
	        });
		} else {
			layer.alert('请至少勾选一条商品');
		}
     });
		 
	//拉取聚水潭采购入库单   
    $('#pulljstputorder').click(function () {
		submit = 2
        layer.open({
            type: 2,
            title: '拉取聚水潭采购入库单',
            area: ['850px', '600px'],
            anim: 5,
            content: Feng.ctxPath + '/toolOrderPut/topulljstputorder',
            end: function () {
				if(submit == 1){
        			table.reload(ToolOrderPut.tableId);
				}
            }
        });
    });
		 
	//拉取聚水潭退货明细   
    $('#pulljstreturngoods').click(function () {
		submit = 2
        layer.open({
            type: 2,
            title: '拉取聚水潭退货入库明细',
            area: ['850px', '600px'],
            anim: 5,
            content: Feng.ctxPath + '/toolOrderPut/topulljstreturngoods',
            end: function () {
				if(submit == 1){
        			table.reload(ToolOrderPut.tableId);
				}
            }
        });
    });

	 // 导入excel
	 $('#btnExpimport').click(function () {
		submit = 2
        layer.open({
            type: 2,
            title: '入库信息导入',
            area: ['1000px', '600px'],
            anim: 5,
            content: Feng.ctxPath + '/toolOrderPut/toimportExcel',
            end: function () {
				if(submit == 1){
        			table.reload(ToolOrderPut.tableId);
				}
            }
        });
	 });

     // 批量作废
     $('#btnTovoid').click(function () {
    	var checkStatus = table.checkStatus('toolOrderPutTable');
        data = checkStatus.data;
        if (data.length>0) {
            var ids = [];
            for (var i = 0; i < data.length; i++) {
            	ids.push(data[i].id);
			}
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/toolOrderPut/tovoid?ids="+ids, function (data) {
					if(data.success){
	                    Feng.success("作废成功!");
	                	table.reload(ToolOrderPut.tableId);
					} else {
                    	Feng.error("作废失败!" + data.message + "!");
					}
                }, function (data) {
                    Feng.error("作废失败!" + data.responseJSON.message + "!");
                });
                ajax.start();
            };
            Feng.confirm("是否作废选中订单?", operation);
		} else {
			layer.alert('请至少选中一条数据');
		}
     });

    /**
     * 撤回
     */
    ToolOrderPut.revoke = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/toolOrderPut/revoke?id="+data.id, function (data) {
                if(data.success){
                	Feng.success("撤回成功!");
                	table.reload(ToolOrderPut.tableId);
                } else {
                    Feng.error("撤回失败!" + data.message + "!");
                }
            }, function (data) {
                Feng.error("撤回失败!" + data.responseJSON.message + "!");
            });
            ajax.start();
        };
        Feng.confirm("确认撤回选中订单?", operation);
    };
    
    // 发起
    ToolOrderPut.launch = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/toolOrderPut/launch?id="+data.id, function (data) {
                if(data.success){
                	Feng.success("发起成功!");
                	table.reload(ToolOrderPut.tableId);
                } else {
                    Feng.error("发起失败!" + data.message + "!");
                }
            }, function (data) {
                Feng.error("发起失败!" + data.responseJSON.message + "!");
            });
            ajax.start();
        };
        Feng.confirm("重新发起选中订单?", operation);
    };

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        ToolOrderPut.search();
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        ToolOrderPut.openAddDlg();
    });

    // 导出excel
    $('#btnExp').click(function () {
        ToolOrderPut.exportExcel();
    });

    // 工具条点击事件
    table.on('tool(' + ToolOrderPut.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            ToolOrderPut.openEditDlg(data);
        } else if (layEvent === 'launch') {
        	ToolOrderPut.launch(data);
        } else if (layEvent === 'revoke') {
        	ToolOrderPut.revoke(data);
        } 
    });
    
    /**
     * 初始化表格的列
     */
    ToolOrderPutDetailed.initColumn = function () {
        return [[
            {field: 'id', hide: true, title: '主键'},
            {field: 'detailedGoodsname', title: '名称', style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'goodsNumber', title: '编号', style:'background-color: #dbf1e1;font-weight: 600;', totalRowText: '合计：'},
            {field: 'detailedPutnum', title: '数量', totalRow: true, style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'detailedPutweight', title: '重量', totalRow: true},
            {field: 'detailedPutvolume', title: '体积', totalRow: true},
            {field: 'detailedUnitprice', title: '单价'},
            {field: 'detailedMoney', title: '金额', totalRow: true},
            {field: 'detailedLargeclass', title: '商品大类'},
            {field: 'goodsUnit', title: '单位'},
            {field: 'goodsSpecs', title: '规格'},
            {fixed: 'right',align: 'center', toolbar: '#tableBarDetailed', title: '操作'}
        ]];
    };

    // 单击行事件
    table.on('row(' + ToolOrderPut.tableId + ')', function (obj) {
        var data = obj.data;
		$('div[lay-id="' + ToolOrderPut.tableId + '"]').find(".layui-table-body tr ").attr({ "style": "background:#FFFFFF" });//其他tr恢复原样
		$('div[lay-id="' + ToolOrderPut.tableId + '"]').find(obj.tr.selector).attr({ "style": "background:#e6e6e6" });//改变当前tr颜色
        orderPut(data);
    });
    
    function orderPut(data){
    	var putNumber;
    	if (data!=null) {
    		$("#putDetailedNumber").val(data.putNumber);
    		putNumber = data.putNumber;
		} else {
			putNumber = 'nodata';
		}
        // 渲染商品明细表格
        var tableResult = table.render({
            elem: '#' + ToolOrderPutDetailed.tableId,
            url: Feng.ctxPath + '/toolOrderPutDetailed/list?putDetailedNumber=' + putNumber,
            page: true,
            limit: 40,
            height: 400,
            toolbar: '#toolbarfromDetailed',
            cellMinWidth: 100,
            totalRow: true ,//开启合计行
            cols: ToolOrderPutDetailed.initColumn()
        });

        /**
         * 点击查询按钮
         */
    	ToolOrderPutDetailed.search = function () {
            var queryData = {};
            queryData['condition'] = $("#condition2").val();
            table.reload(ToolOrderPutDetailed.tableId, {
                where: queryData, page: {curr: 1},
                 done:function () {
                     // 搜索按钮点击事件
                     $('#btnSearchDetailed').click(function () {
                    	 ToolOrderPutDetailed.search();
                     });
			        $('#btnAddDetailed').click(function () {
			        	ToolOrderPutDetailed.addDetailed();
			        });
                }
            });
        };

    	ToolOrderPutDetailed.addDetailed = function () {
            layer.open({
                type: 2,
                title: '明细录入',
                area: ['1000px', '750px'],
                anim: 5,
                content: Feng.ctxPath + '/toolOrderPutDetailed/add?putDetailedNumber=' + data.putNumber+"&putCustomerId="+data.putCustomerId,
                end: function () {
                	orderPut(data);
                }
            });
        };

        // 工具条点击事件
        table.on('tool(' + ToolOrderPutDetailed.tableId + ')', function (obj) {
            var data2 = obj.data;
            var layEvent = obj.event;

            if (layEvent === 'editDetailed') {
                ToolOrderPutDetailed.openEditDlg(data2);
            } else if (layEvent === 'deleteDetailed') {
                ToolOrderPutDetailed.onDeleteItem(data2);
            }
        });

        // 修改按钮点击事件
        ToolOrderPutDetailed.openEditDlg = function (data2) {
            layer.open({
                type: 2,
                title: '明细修改',
                area: ['1000px', '750px'],
                anim: 5,
                content: Feng.ctxPath + '/toolOrderPutDetailed/edit?id='+data2.id+"&putDetailedNumber="+data.putNumber+"&putCustomerId="+data.putCustomerId,
                end: function () {
                	orderPut(data);
                }
            });
        };

        // 删除按钮点击事件
        ToolOrderPutDetailed.onDeleteItem = function (data2) {
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/toolOrderPutDetailed/delete", function (data2) {
                    Feng.success("删除成功!");
                	orderPut(data);
                }, function (data) {
                    Feng.error("删除失败!" + data2.responseJSON.message + "!");
                });
                ajax.set("id", data2.id);
                ajax.start();
            };
            Feng.confirm("是否删除?", operation);
        };

        // 搜索按钮点击事件
        $('#btnSearchDetailed').click(function () {
        	ToolOrderPutDetailed.search();
        });

        $('#btnAddDetailed').click(function () {
        	ToolOrderPutDetailed.addDetailed();
        });
    }
});
